package com.topisv.tms.utils.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.topisv.tms.entity.BackupTask;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.ShippedBatch;
import com.topisv.tms.rest.entity.Batch;
import com.topisv.tms.service.BackupTaskService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.shipped.ShippedBatchService;

import net.sf.json.JSONObject;
@Component
public class SynchroSendBatchMessage implements Runnable {

	private static final Logger log = LoggerFactory.getLogger(SynchroSendBatchMessage.class);
	
	@Autowired
	private BackupTaskService backupTaskService;
	@Autowired
	private ShippedBatchService shippedBatchService;
	@Autowired
	private CustomersService customersService;

	public SynchroSendBatchMessage() {
		super();
	}
	@Override
	public void run() {
		while (true) {
			String message = null;
			try {
				message = SynchroShippedBatchQueue.takeSendBatchQueue();
				this.sendBatch(message);
			} catch (Exception e) {
				log.error("error",e);
				
			}
		}

	}
	
	/**
	 * 推送出库批次
	 * @param backupTaskCode
	 * @throws Exception
	 */
	private void sendBatch(String backupTaskCode) throws Exception{
		try {
			BackupTask task=this.backupTaskService.findByBackupTaskCode(backupTaskCode);
			if("finish".equals(task.getStatus())){
				Batch batch = shippedBatchService.getBatch(task.getBatchCode(), task.getCustomerCode());
				Customers customers=customersService.findByCustomerCode(task.getCustomerCode());
				JSONObject json = JSONObject.fromObject(batch);
				String result = HttpPost.putShippedBatch(customers,json.toString());
				json = JSONObject.fromObject(result);
				if ("1".equals(json.get("status"))) {
					ShippedBatch shippedBatch=shippedBatchService.findByBatchCode(task.getBatchCode());
					if(!"finish".equals(shippedBatch.getStatus())){
						shippedBatch.setStatus("finish");
						shippedBatchService.save(shippedBatch);
						if("1".equals(customers.getPassBack())){
//							SynchroShippedBatchQueue.putSynchroQueue(shippedBatch.getBackupTaskCode());//发货
						}
					}
				} 
			}
		} catch (Exception e) {
			throw e;
		}
	}

}
